package com.farm.sfile.utils;

import java.util.UUID;

import org.apache.commons.lang.StringUtils;

import com.farm.core.auth.domain.LoginUser;
import com.farm.parameter.FarmParameterService;
import com.farm.util.cache.FarmCacheName;
import com.farm.util.cache.FarmCaches;

/**
 * 访问授权令牌
 * 
 * @author Wd
 *
 */
public class VisitTokens {

	/**
	 * 获取资源授权，此时未绑定用户，当首次访问时绑定用户
	 * 
	 * @param fileid
	 * @return
	 */
	public static String getToken(String appid) {
		String tokenKey = UUID.randomUUID().toString().replace("-", "");
		FarmCaches.getInstance().putCacheData(tokenKey, appid + ":" + "none", FarmCacheName.wlp_token);
		return tokenKey;
	}

	public static void checkToken(String token, String appid, LoginUser currentUser) {
		//是否启用token校验
		if (!FarmParameterService.getInstance().getParameterBoolean("config.doc.visit.token.able")) {
			return;
		}
		if (StringUtils.isBlank(token)) {
			throw new RuntimeException("the token is null!");
		}
		String idAndUserId = (String) FarmCaches.getInstance().getCacheData(token, FarmCacheName.wlp_token);
		if (StringUtils.isBlank(idAndUserId)) {
			throw new RuntimeException("the token(" + token + ") is not exist!");
		}
		String[] datas = idAndUserId.split(":");
		if (datas.length != 2) {
			throw new RuntimeException("the token format is error!");
		}
		if (!datas[0].equals(appid)) {
			throw new RuntimeException("the token appid is error!");
		}
		if (!datas[1].equals("none")) {
			if (currentUser == null) {
				throw new RuntimeException("the user is null by check token!");
			}
			if (!datas[1].equals(currentUser.getId())) {
				throw new RuntimeException("the user is error by check token!");
			}
		} else {
			if (currentUser != null) {
				FarmCaches.getInstance().putCacheData(token, appid + ":" + currentUser.getId(),
						FarmCacheName.wlp_token);
			}
		}
	}

}
